<template>
	<view>
		<view class="fab-login-box">
			<view class="item" v-for="(item,index) in servicesList" :key="index"
				@click="item.path?toPage(item.path):login_before(item.id,false)">
				<image class="logo" :src="item.logo" mode="scaleToFill"></image>
				<text class="login-title">{{item.text}}</text>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, computed, watch, onMounted } from 'vue';
	import config from '@/uni_modules/uni-id-pages/config.js';
	const 同意 = defineModel('同意');
	// console.log('同意: ', 同意);
	const props = defineProps({
		父组件: {
			type: Object,
			default: {}
		}
	});
	// 定义响应式数据
	const servicesList = ref([{
			"id": "username",
			"text": "账号登录",
			"logo": "/uni_modules/uni-id-pages/static/login/uni-fab-login/user.png",
			"path": "/uni_modules/uni-id-pages/pages/login/login-withpwd"
		},
		{
			"id": "smsCode",
			"text": "短信验证码",
			"logo": "/uni_modules/uni-id-pages/static/login/uni-fab-login/sms.png",
			"path": "/uni_modules/uni-id-pages/pages/login/login-withoutpwd?type=smsCode"
		},
		{
			"id": "weixin",
			"text": "微信登录",
			"logo": "/uni_modules/uni-id-pages/static/login/uni-fab-login/weixin.png",
		},
		{
			"id": "huawei",
			"text": "华为登录",
			"logo": "/uni_modules/uni-id-pages/static/login/uni-fab-login/huawei.png",
			"path": "/uni_modules/uni-id-pages/pages/login/login-withoutpwd?type=huawei"
		},
		{
			"id": "huaweiMobile",
			"text": "华为账号一键登录",
			"logo": "/uni_modules/uni-id-pages/static/login/uni-fab-login/huawei.png",
			"path": "/uni_modules/uni-id-pages/pages/login/login-withoutpwd?type=huaweiMobile"
		},
		// #ifndef MP-WEIXIN
		{
			"id": "apple",
			"text": "苹果登录",
			"logo": "/uni_modules/uni-id-pages/static/uni-fab-login/apple.png",
		},
		{
			"id": "univerify",
			"text": "一键登录",
			"logo": "/uni_modules/uni-id-pages/static/app/uni-fab-login/univerify.png",
		},
		{
			"id": "taobao",
			"text": "淘宝登录", //暂未提供该登录方式的接口示例
			"logo": "/uni_modules/uni-id-pages/static/app/uni-fab-login/taobao.png",
		},
		{
			"id": "facebook",
			"text": "脸书登录", //暂未提供该登录方式的接口示例
			"logo": "/uni_modules/uni-id-pages/static/app/uni-fab-login/facebook.png",
		},
		{
			"id": "alipay",
			"text": "支付宝登录", //暂未提供该登录方式的接口示例
			"logo": "/uni_modules/uni-id-pages/static/app/uni-fab-login/alipay.png",
		},
		{
			"id": "qq",
			"text": "QQ登录", //暂未提供该登录方式的接口示例
			"logo": "/uni_modules/uni-id-pages/static/app/uni-fab-login/qq.png",
		},
		{
			"id": "google",
			"text": "谷歌登录", //暂未提供该登录方式的接口示例
			"logo": "/uni_modules/uni-id-pages/static/app/uni-fab-login/google.png",
		},
		{
			"id": "douyin",
			"text": "抖音登录", //暂未提供该登录方式的接口示例
			"logo": "/uni_modules/uni-id-pages/static/app/uni-fab-login/douyin.png",
		},
		{
			"id": "sinaweibo",
			"text": "新浪微博", //暂未提供该登录方式的接口示例
			"logo": "/uni_modules/uni-id-pages/static/app/uni-fab-login/sinaweibo.png",
		}
		// #endif
	]);

	const univerifyStyle = ref({
		"fullScreen": true,
		"backgroundColor": "#ffffff",
		"buttons": {
			"iconWidth": "45px",
			"list": []
		},
		"privacyTerms": {
			"defaultCheckBoxState": false,
			"textColor": "#BBBBBB",
			"termsColor": "#5496E3",
			"prefix": "我已阅读并同意",
			"suffix": "并使用本机号码登录",
			"privacyItems": []
		}
	});

	// 计算属性
	const agreements = computed(() => {
		if (!config.agreements) {
			return [];
		}
		const { serviceUrl, privacyUrl } = config.agreements;
		return [{
				url: serviceUrl,
				title: "用户服务协议"
			},
			{
				url: privacyUrl,
				title: "隐私政策条款"
			}
		];
	});

	function getRoute(n = 0) {
		let pages = getCurrentPages();
		if (n > pages.length) {
			return ''
		}
		return '/' + pages[pages.length - n].route
	}

	// 监听 同意 的变化
	watch(同意, (newValue) => {
		console.log('同意变化了 newValue: ', newValue);
		univerifyStyle.value.privacyTerms.defaultCheckBoxState = newValue;
	});

	onMounted(async () => {
		let loginTypes = config.loginTypes;
		let filteredServicesList = servicesList.value.filter(item => {
			// #ifndef APP
			if (item.id === 'apple') {
				return false;
			}
			// #endif
			// #ifdef APP
			if (item.id === 'apple' && uni.getSystemInfoSync().osName !== 'ios') {
				return false;
			}
			// #endif
			return loginTypes.includes(item.id);
		});

		if (loginTypes.includes('univerify')) {
			univerifyStyle.value.privacyTerms.privacyItems = agreements.value;
			filteredServicesList.forEach(({ id, logo, path }) => {
				if (id !== 'univerify') {
					univerifyStyle.value.buttons.list.push({
						"iconPath": logo,
						"provider": id,
						path
					});
				}
			});
		}

		servicesList.value = filteredServicesList.filter(item => {
			let path = item.path ? item.path.split('?')[0] : '';
			return path !== getRoute(1);
		});
	});

	// 页面跳转方法
	const toPage = (path, index = 0) => {
		console.log('比较', getRoute(1), getRoute(2), path);
		if (getRoute(1) === path.split('?')[0] && getRoute(1) ===
			'/uni_modules/uni-id-pages/pages/login/login-withoutpwd') {
			let loginType = path.split('?')[1].split('=')[1];
			uni.$emit('uni-id-pages-setLoginType', loginType);
		} else if (getRoute(2) === path) {
			uni.navigateBack();
		} else if (getRoute(1) !== path) {
			if (index === 0) {
				uni.navigateTo({
					url: path,
					animationType: 'slide-in-left',
					complete(e) {
						// console.log(e);
					}
				});
			} else {
				uni.redirectTo({
					url: path,
					animationType: 'slide-in-left',
					complete(e) {
						// console.log(e);
					}
				});
			}
		} else {
			console.log('出乎意料的情况,path：' + path);
		}
	};

	// 登录前的处理方法
	const login_before = async (type, navigateBack = true, options = {}) => {
		console.log("type, options", type, options);
		if (["qq", "xiaomi", "sinaweibo", "taobao", "facebook", "google", "alipay", "douyin"].includes(type)) {
			return uni.showToast({
				title: '该登录方式暂未实现，欢迎提交pr',
				icon: 'none',
				duration: 3000
			});
		}

		// #ifdef APP
		let isAppExist = true;
		await new Promise((callback) => {
			uni.getProvider({
				service: 'oauth',
				success: (res) => {
					const provider = res.providers.find(item => item.id === type);
					console.log('res', res);
					if (provider) {
						isAppExist = provider?.isAppExist ?? true;
						callback();
					} else {
						return uni.showToast({
							title: '当前设备不支持此登录，请选择其他登录方式',
							icon: 'none',
							duration: 3000
						});
					}
				},
				fail: () => {
					throw new Error('获取服务供应商失败：' + JSON.stringify(err));
				}
			});
		});
		// #endif

		if (
			// #ifdef APP
			!isAppExist
			// #endif
			// #ifndef APP
			["univerify", "apple"].includes(type)
			// #endif
		) {
			return uni.showToast({
				title: '当前设备不支持此登录，请选择其他登录方式',
				icon: 'none',
				duration: 3000
			});
		}

		let needAgreements = (config?.agreements?.scope || []).includes('register');
		if (type !== 'univerify' && needAgreements && !同意.value) {
			let agreementsRef = props.父组件.agreementsRef;
			return agreementsRef.popup(() => {
				登录一同意之后部分(type, navigateBack, options);
			});
		}
		登录一同意之后部分(type, navigateBack, options)
	};

	const 登录一同意之后部分 = async (type, navigateBack = true, options = {}) => {
		// #ifdef H5
		if (type === 'weixin') {
			console.log('微信h5下面登录？');
			const baseUrl = import.meta.env.BASE_URL;
			let redirectUrl = location.protocol +
				'//' +
				location.host +
				baseUrl.replace(/\/$/, '') +
				(window.location.href.includes('#') ? '/#' : '') +
				'/uni_modules/uni-id-pages/pages/login/login-withoutpwd?is_weixin_redirect=true&type=weixin';

			let ua = window.navigator.userAgent.toLowerCase();
			if (ua.match(/MicroMessenger/i) === 'micromessenger') {
				return window.open(`https://open.weixin.qq.com/connect/oauth2/authorize?
                        appid=${config.appid.weixin.h5}
                        &redirect_uri=${encodeURIComponent(redirectUrl)}
                        &response_type=code
                        &scope=snsapi_userinfo
                        &state=STATE&connect_redirect=1#wechat_redirect`);
			} else {
				return location.href = `https://open.weixin.qq.com/connect/qrconnect?appid=${config.appid.weixin.web}
                        &redirect_uri=${encodeURIComponent(redirectUrl)}
                        &response_type=code&scope=snsapi_login&state=STATE#wechat_redirect`;
			}
		}
		// #endif

		uni.showLoading({
			// #ifdef MP-HARMONY
			title: "正在登录",
			// #endif
			mask: true
		});

		if (type === 'univerify') {
			let univerifyManager = uni.getUniverifyManager();
			let clickAnotherButtons = false;
			let onButtonsClickFn = async (res) => {
				console.log('点击了第三方登录，provider：', res, res.provider, univerifyStyle.value.buttons.list);
				clickAnotherButtons = true;
				let checkBoxState = await uni.getCheckBoxState();
				// 同步一键登录弹出层隐私协议框是否打勾
				同意.value = checkBoxState.state;
				let { path } = univerifyStyle.value.buttons.list[res.index];
				if (path) {
					if (getRoute(1).includes('login-withoutpwd') && path.includes('login-withoutpwd')) {
						getParentComponent().showCurrentWebview();
					}
					toPage(path, 1);
					closeUniverify();
				} else {
					if (同意.value) {
						closeUniverify();
						setTimeout(() => {
							login_before(res.provider);
						}, 500);
					} else {
						uni.showToast({
							title: "你未同意隐私政策协议",
							icon: 'none',
							duration: 3000
						});
					}
				}
			};

			function closeUniverify() {
				uni.hideLoading();
				univerifyManager.close();
				univerifyManager.offButtonsClick(onButtonsClickFn);
			}

			univerifyManager.onButtonsClick(onButtonsClickFn);
			return univerifyManager.login({
				"univerifyStyle": univerifyStyle.value,
				success: (res) => {
					login(res.authResult, 'univerify');
				},
				fail: (err) => {
					console.log(err);
					if (!clickAnotherButtons) {
						uni.navigateBack();
					}
				},
				complete: async (e) => {
					uni.hideLoading();
					// 同步一键登录弹出层隐私协议框是否打勾
					// 同意.value = (await uni.getCheckBoxState())[1].state;
					univerifyManager.offButtonsClick(onButtonsClickFn);
				}
			});
		}

		if (type === 'weixinMobile' || type === 'huaweiMobile') {
			return login({
				phoneCode: options.phoneNumberCode
			}, type);
		}

		uni.login({
			"provider": type,
			"onlyAuthorize": true,
			// #ifdef APP
			"univerifyStyle": univerifyStyle.value,
			// #endif
			success: async (e) => {
				if (type === 'apple') {
					let res = await getUserInfo({
						provider: "apple"
					});
					Object.assign(e.authResult, res.userInfo);
					uni.hideLoading();
				}
				login(['huawei', 'weixin'].includes(type) ? {
					code: e.code
				} : e.authResult, type);
			},
			fail: async (err) => {
				console.error(JSON.stringify(err));
				uni.showModal({
					content: `登录失败; code: ${err.errCode || -1}`,
					confirmText: "知道了",
					showCancel: false
				});
				uni.hideLoading();
			}
		});
	};

	// 登录方法
	const login = (params, type) => {
		console.log({ params, type });
		let action = 'loginBy' + type.trim().replace(type[0], type[0].toUpperCase());
		const uniIdCo = uniCloud.importObject("uni-id-co", {
			customUI: true
		});
		uniIdCo[action](params).then((result) => {
			uni.showToast({
				title: '登录成功',
				icon: 'none',
				duration: 2000
			});
			// #ifdef H5
			result.loginType = type;
			// #endif
			mutations.loginSuccess(result);
		}).catch((e) => {
			uni.showModal({
				content: e.message,
				confirmText: "知道了",
				showCancel: false
			});
		}).finally(e => {
			if (type == 'univerify') {
				uni.closeAuthView()
			}
			uni.hideLoading()
		})
	}
</script>

<style lang="scss">
	/* #ifndef APP-NVUE */
	.fab-login-box,
	.item {
		display: flex;
		box-sizing: border-box;
		flex-direction: column;
	}

	/* #endif */

	.fab-login-box {
		flex-direction: row;
		flex-wrap: wrap;
		width: 750rpx;
		justify-content: space-around;
		position: fixed;
		left: 0;
	}

	.item {
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: 200rpx;
		cursor: pointer;
	}

	/* #ifndef APP-NVUE */
	@media screen and (min-width: 690px) {
		.fab-login-box {
			max-width: 500px;
			margin-left: calc(50% - 250px);
		}

		.item {
			height: 160rpx;
		}
	}

	@media screen and (max-width: 690px) {
		.fab-login-box {
			bottom: 10rpx;
		}
	}

	/* #endif */

	.logo {
		width: 60rpx;
		height: 60rpx;
		max-width: 40px;
		max-height: 40px;
		border-radius: 100%;
		border: solid 1px #F6F6F6;
	}

	.login-title {
		text-align: center;
		margin-top: 6px;
		color: #999;
		font-size: 10px;
		width: 80px;
	}
</style>